﻿using System;

namespace PortalCurriculo.MvcWebUI.Helpers
{
    public static class GeoHelper
    {
        //public const double EarthRadiusInMiles = 3956.0;
        //public const double EarthRadiusInKilometers = 6367.0;
        //public static double ToRadian(double val) { return val * (Math.PI / 180); }
        //public static double DiffRadian(double val1, double val2) { return ToRadian(val2) - ToRadian(val1); }
        ///// <summary>
        ///// Calculate the distance between two geocodes. Defaults to using Miles.
        ///// </summary>
        //public static double CalcDistance(double lat1, double lng1, double lat2, double lng2)
        //{
        //    return CalcDistance(lat1, lng1, lat2, lng2, GeoCodeCalcMeasurement.Miles);
        //}
        ///// <summary>
        ///// Calculate the distance between two geocodes.
        ///// </summary>
        //public static double CalcDistance(double lat1, double lng1, double lat2, double lng2, GeoCodeCalcMeasurement m)
        //{
        //    double radius = GeoCodeCalc.EarthRadiusInMiles;
        //    if (m == GeoCodeCalcMeasurement.Kilometers) { radius = GeoCodeCalc.EarthRadiusInKilometers; }
        //    return radius * 2 * Math.Asin(Math.Min(1, Math.Sqrt((Math.Pow(Math.Sin((DiffRadian(lat1, lat2)) / 2.0), 2.0) + Math.Cos(ToRadian(lat1)) * Math.Cos(ToRadian(lat2)) * Math.Pow(Math.Sin((DiffRadian(lng1, lng2)) / 2.0), 2.0)))));
        //}

        public static int CalculateDistance(double lat1, double lon1, double lat2, double lon2, char unit)
        {
            double theta = lon1 - lon2;
            double dist = Math.Sin(Deg2Rad(lat1)) * Math.Sin(Deg2Rad(lat2)) + Math.Cos(Deg2Rad(lat1)) * Math.Cos(Deg2Rad(lat2)) * Math.Cos(Deg2Rad(theta));
            dist = Math.Acos(dist);
            dist = Rad2Deg(dist);
            dist = dist * 60 * 1.1515;

            if (unit == 'K')
                dist = dist * 1.609344;
            else if (unit == 'N')
                dist = dist * 0.8684;

            return Convert.ToInt32(dist);
        }

        private static double Deg2Rad(double deg)
        {
            return (deg * Math.PI / 180.0);
        }

        private static double Rad2Deg(double rad)
        {
            return (rad / Math.PI * 180.0);
        }
    }

    public enum GeoCodeCalcMeasurement
    {
        Miles = 0,
        Kilometers = 1
    }
}